<template>
	<view class="loginView">
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<button class="button" type="primary" @click="getUserInfo">一键登录</button>
		<text class="tips">登录后尽享更多权益</text>
	</view>
</template>

<script>
	import {mapState,mapMutations} from 'vuex'
	export default {
		name:"my-login",
		data() {
			return {
				
			};
		},
		computed: {
			...mapState('m_user',['redirectInfo'])
		},
		methods:{
			...mapMutations('m_user',['updateUserinfo','updateToken','updateRedirectInfo']),
			//获取微信用户的基本信息
			 getUserInfo(){
				uni.getUserProfile({
					desc: '用于完善会员授权', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				       success: (res) => {
						   console.log('获取授权：',res)
						   this.updateUserinfo(res.userInfo)
						   
						   this.getToken(res)
				     },
					 fail: (res) => {
						   console.log('授权失败：',res)
						   if (res.errMsg === 'getUserProfile:fail auth deny') return uni.$showErrMsg('您取消了授权登录！')
				     }
				})
			},
			async getToken(info){
				// 获取code的值
				const [err, res] = await uni.login().catch(err => err)
				console.log('登录获取code：',res ,'err',err)
				if(err || res.errMsg !== 'login:ok')return uni.$showErrMsg('登录失败！')
				
				const query = {
					code: res.code,
					encryptedData: info.encryptedData,
					rawData: info.rawData,
					iv: info.iv,
					signature: info.signature
				}
				console.log('info',info,'query',query)
				const {data: loginResult } = await uni.$http.post('/users/wxlogin', query)
				console.log('loginResult',loginResult,'this.redirectInfo',this.redirectInfo)
				if(loginResult.meta.status !== 200) return uni.$showErrMsg(loginResult.meta.msg)
				uni.$showErrMsg('登录成功！')
				// 直接把token保存在vuex中
				this.updateToken(loginResult.message.token)
				
				this.navigateBack()
			},
			navigateBack() {
				if(this.redirectInfo && this.redirectInfo.openType === 'switchTab') {
					uni.switchTab({
						url: this.redirectInfo.from,
						complete:()=> {
							this.updateRedirectInfo(null)
						}
					})
				}
			}	
		} 
	}
</script>

<style lang="scss">
	.loginView {
		height: 750rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background: #f8f8f8;
		position: relative;
		overflow: hidden;
		&::after{
			content: '';
			display: block;
			width: 100%;
			height: 40px;
			background: white;
			border-radius: 100%;
			position: absolute;
			bottom: 0;
			transform: translateY(50%);
			
		}
		.button {
			background: #C00000;
			margin: 15px auto;
			border-radius: 20px;
			font-size: 15px;
			width: 90%;
		}
		.tips{
			font-size: 13px;
			color: gray;
		}
	}
	
</style>
